//设置根路径
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

// 获取元素
const tb = document.querySelector('#tb');

// 封装渲染页面函数
async function renderBooks() {
  const { data: res } = await axios.get('/api/getbooks')
  const { data } = res
  tb.innerHTML =  data.map((item) => {
    return `
    <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>
    `
   }).join('')
}
renderBooks()

// 添加表单提交事件
const form = document.querySelector('form');
form.addEventListener('submit', async function (e) {
e.preventDefault()
  // 利用serialize方法获取表单name
  const data = serialize(form, { hash: true })
  const { data: res } = await axios.post('/api/addbook', data)
  alert(res.msg)
  if (res.status !== 201) return
  renderBooks()
  form.reset()
})

// 删除
tb.addEventListener('click', async function (e) {
  if (e.target.tagName = 'A') {
    const id = e.target.dataset.id
    const { data: res } = await axios.get('/api/delbook', { params: { id } })
      renderBooks()
   }
});

// 查询
const search = document.querySelector('#search');
search.addEventListener('click', async function (e) {
    // 阻止默认行为
    e.preventDefault()
    const data = serialize(form, { hash: true })
    // console.log(data);
  const { data:res } = await axios.get('/api/getbooks', {
    params:data   
  })
  tb.innerHTML = res.data.map((item) => {
    return `
    <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>
    `
   }).join('')
  });
  
